package sword;

/**
 * @Author: 海琳琦
 * @Date: 2022/5/28 20:43
 * https://leetcode.cn/problems/ping-heng-er-cha-shu-lcof/
 */
public class Title55II {

    class TreeNode {
        int val;

        TreeNode left;

        TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    boolean flag;

    public boolean isBalanced(TreeNode root) {
        flag = true;
        backTracking(root);
        return flag;
    }

    private int backTracking(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = backTracking(root.left);
        if (left == -1) {
            return -1;
        }
        int right = backTracking(root.right);
        if (right == -1) {
            return -1;
        }
        int gap = Math.abs(left - right);
        if (gap > 1) {
            flag = false;
            return -1;
        }
        return Math.max(left, right) + 1;
    }

    public static void main(String[] args) {

    }
}
